var util = require('../../../utils/util.js');
var api = require('../../../config/api.js');
var Map = require("../../../utils/map.js");
var dateTimePicker = require('../../../utils/dateTimePicker.js');

Page({
    /**
     * 页面的初始数据
     */
    data: {
        auditPoster: [],
        showPoster: [],
        disabled: false,
        mall:0,
        categoryList: [],
        pickerindex:0,
        categoryId:'',
        name:'',
        stock:'',
        editId:'',
        buyingPrice:'',
        files:[],
        manufactureDate:'',
        shelfLife:'',
        onSaleType:2,
        saleStartTime:'',
        saleEndTime:'',
        startDate:'',
        endDate:'',
        startTime:'',
        endTime:'',
        dateTimeArray: null,
        dateTime: null,
        dateTimeArray1: null,
        dateTime1: null,
        startYear: 2000,
        endYear: 2050,
        show:false,
    },

    bindStartDateChange: function(e) {
        // console.log('picker发送选择改变，携带值为', e.detail.value)
        this.setData({
            startDate:e.detail.value,
            saleStartTime: e.detail.value+" 00:00:00"
        })
    },
    bindEndDateChange: function(e) {
        // console.log('picker发送选择改变，携带值为', e.detail.value)
        this.setData({
            endDate:e.detail.value,
            saleEndTime: e.detail.value+" 23:59:59"
        })
    },
    bindStartTimeChange: function(e) {
        // console.log('picker发送选择改变，携带值为', e.detail.value)
        this.setData({
            startTime: e.detail.value
        })
    },
    bindEndTimeChange: function(e) {
        // console.log('picker发送选择改变，携带值为', e.detail.value)
        this.setData({
            endTime: e.detail.value
        })
    },
    bindDateChange: function(e) {
        // console.log('picker发送选择改变，携带值为', e.detail.value)
        this.setData({
            manufactureDate: e.detail.value
        })
    },
    bindPickerChange: function(e) {
        let that = this
        //console.log('picker发送选择改变，携带值为', e.detail)
        this.setData({
            pickerindex: e.detail.value,
            categoryId:that.data.categoryList[e.detail.value].id
        })
    },
    radioChange: function(e){
        this.setData({
            mall: e.detail.value
        })
    },
    radioChangeType: function(e){
        this.setData({
            onSaleType: e.detail.value
        })
    },
    changeDate(e){
        this.setData({ date:e.detail.value});
    },
    changeTime(e){
        this.setData({ time: e.detail.value });
    },
    changeDateTime(e){
        this.setData({ dateTime: e.detail.value });
    },
    changeDateTime1(e) {
        this.setData({ dateTime1: e.detail.value });
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {

        this.categoryList()
        if(options.data){

            let data = JSON.parse(options.data)
            console.log(data)
            let auditPoster = []
            data.auditPoster.forEach(item=>{
                auditPoster.push({
                    url:item,
                    thumb:item,
                    type:'image'
                })
            })
            let showPoster = []
            data.showPoster.forEach(item=>{
                showPoster.push({
                    url:item,
                    thumb:item,
                    type:'image'
                })
            })
            this.setData({
                editId : data.commodityId,
                categoryId :data.categoryId,
                name:data.name,
                stock:data.stock,
                mall:data.isMail?1:0,
                auditPoster:auditPoster,
                showPoster:showPoster,
                buyingPrice:data.buyingPrice,
                manufactureDate:data.manufactureDate==null?'请选择生产日期':data.manufactureDate,
                shelfLife:data.shelfLife,
                onSaleType:data.onSaleType.value
            })
            if(data.saleEndTime != '' && data.saleEndTime !=null){
                this.setData({
                    startDate:data.saleStartTime.split(' ')[0],
                    startTime:data.saleStartTime.split(' ')[1].split(':')[0]+':'+data.saleStartTime.split(' ')[1].split(':')[1],
                    endDate:data.saleEndTime.split(' ')[0],
                    endTime:data.saleEndTime.split(' ')[1].split(':')[0]+':'+data.saleEndTime.split(' ')[1].split(':')[1]
                })
            }
        }
        this.setData({
            selectFile: this.selectFile.bind(this),
            uplaodFile: this.uplaodFile.bind(this)
        });
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {},

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {},

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {
    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {},

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {},

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {},
    // 分类列表
    categoryList() {
        let that = this
        wx.showLoading({
            title: "Loading..."
        });
        util.request(api.supplier.categoryList,{}, "GET")
            .then((res) => {
                console.log(res)
                that.setData({
                    categoryList:res.result
                })
                if(that.data.categoryId != ''){
                    that.data.categoryList.forEach((value,index)=> {
                        //console.log(value.id)
                        if(value.id == that.data.categoryId){
                            that.setData({
                                pickerindex:index
                            })
                        }
                    })
                }
                wx.hideLoading();
            })
            .catch((err) => {
                console.log(err)
                wx.hideLoading();
                wx.showToast({
                    title: err.message,
                    icon: "none",
                });
            });
    },
    // 后台请求
    applyMember(data) {
        console.log(data)
        wx.showLoading({
            title: "正在提交中",
            icon: "none",
        });
        this.setData({
            disabled: true
        })
        if(this.data.editId != ''){
            data.id = this.data.editId
        }
        util.request(api.supplier.goodsPost, data, "POST")
            .then((res) => {
                console.log("ress", res);
                wx.showToast({
                  title: '提交成功',
                })
                wx.hideLoading();
                wx.navigateBack({
                  delta: 1,
                })
                this.setData({
                    disabled: false
                })
            })
            .catch((err) => {
                console.log("err", err);
                wx.hideLoading();
                this.setData({
                    disabled: false
                })
                wx.showToast({
                    title: err.message,
                    icon: "none",
                });
            });
    },
    // 提交表单
    formSubmit: function (e) {
        const result = this.validForm(e.detail.value);
        if (result) {
            // 验证成功
            const data = this.getParams(e.detail.value);
            console.table(data);
            this.applyMember(data);
        }
    },
    // 表单验证
    validForm(values) {
        let keys = []; //必填选项
        keys = [ "name", "buyingPrice", "stock","shelfLife"]; //必填选项
        console.log(values)
        const {
            auditPoster,
            showPoster,
            manufactureDate,
            startDate,
            endDate,
            startTime,
            onSaleType,
            endTime } = this.data;
        const result = keys.every((item) => values[item]);
        if (!result) {
            wx.showToast({
                title: "还有选项没填哦",
                icon: "none",
            });
            return false;
        }
        if(manufactureDate == ''){
            wx.showToast({
                title: "请选择生产日期",
                icon: "none",
            });
            return false;
        }

        let regPrice = /^(?:0\.\d{0,1}[1-9]|(?!0)\d{1,100}(?:\.\d{0,1}[1-9])?)$/;
        if(!regPrice.test(values.buyingPrice)){
            wx.showToast({
                icon:'none',
                title: '价格格式错误',
            })
            return false;
        }
        let regStock = /^[1-9]\d*$/;
        if(!regStock.test(values.stock)){
            wx.showToast({
                icon:'none',
                title: '库存格式错误',
            })
            return false;
        }
        if(auditPoster.length<3){
            wx.showToast({
                title: "请选择审核图片",
                icon: "none",
            });
            return false;
        }
        if(showPoster.length==0){
            wx.showToast({
                title: "请选择显示图片",
                icon: "none",
            });
            return false;
        }
        return true;
    },
    // 参数处理
    getParams(values) {
        console.log("enter getParams ",values);
        const {
            showPoster,
            auditPoster,
            startDate,
            endDate,
            startTime,
            endTime,
            manufactureDate
        } = this.data;
        const userInfo = wx.getStorageSync("userInfo");
        const auditPosterList = auditPoster.filter(item => {
            if(!item.error){
                return item;
            }
        }).map(item => { return item.url })
        const showPosterList = showPoster.filter(item => {
            if(!item.error){
                return item;
            }
        }).map(item => { return item.url })
        let defaultData = {
            categoryId: '',
            name: "",
            auditPoster: auditPosterList,
            showPoster: showPosterList,
            buyingPrice: "",
            stock: "",
            mall: 1,
            manufactureDate:manufactureDate,
            shelfLife:'',
            saleStartTime:'',
            saleEndTime:'',
            onSaleType:2
        };

        values.mall = values.mall == 1 ? true : false;
        if(values.onSaleType == 2){
            console.log("aaa values.onSaleType",values.onSaleType);
            values.saleStartTime = startDate+' 00:00:00'
            values.saleEndTime = endDate+' 23:59:59'
        } else {
            console.log("bbb values.onSaleType",values.onSaleType);
            values.saleStartTime = ''
            values.saleEndTime = ''
        }
        values.categoryId = this.data.categoryList[this.data.pickerindex].id
        return Object.assign(defaultData, values);
    },
    afterRead(event) {
        let that = this
        const { file } = event.detail;
        console.log(file)
        // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
        wx.uploadFile({
          url: api.leader.uploadImageUrl, // 仅为示例，非真实的接口地址
          filePath: file.url,
          name: 'file',
          success(res) {
            // 上传完成需要更新 fileList
            let data = JSON.parse(res.data);
            const { auditPoster} = that.data;
            auditPoster.push({ ...file, url: data.message });
            that.setData({ auditPoster });
            //console.log(data)
          },
        });
    },
    afterRead1(event) {
    let that = this
    const { file } = event.detail;
    // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
    wx.uploadFile({
        url: api.leader.uploadImageUrl, // 仅为示例，非真实的接口地址
        filePath: file.url,
        name: 'file',
        success(res) {
        // 上传完成需要更新 fileList
        let data = JSON.parse(res.data);
        const { showPoster} = that.data;
        showPoster.push({ ...file, url: data.message });
        that.setData({ showPoster });
        //console.log(res.result)
        },
    });
    },
    // 图片
    chooseImage: function (e) {
        var that = this;
        wx.chooseImage({
            count: 1,
            sizeType: ["original", "compressed"], // 可以指定是原图还是压缩图，默认二者都有
            sourceType: ["album", "camera"], // 可以指定来源是相册还是相机，默认二者都有
            success: function (res) {
                // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
                that.setData({
                    files: that.data.files.concat(res.tempFilePaths),
                });
            },
        });
    },
    previewImage: function (e) {
        wx.hideToast()
        const auditPosterList = this.data.auditPoster.filter(item => {
            if(!item.error){
                return item;
            }
        }).map(item => { return item.thumb})
        console.log(auditPosterList)
        wx.previewImage({
            current: auditPosterList[e.detail.index], // 当前显示图片的http链接
            urls: auditPosterList, // 需要预览的图片http链接列表
        });
    },
    previewImage1: function (e) {
        wx.hideToast()
        const showPosterList = this.data.showPoster.filter(item => {
            if(!item.error){
                return item;
            }
        }).map(item => { return item.thumb })
        wx.previewImage({
            current: e.detail.index, // 当前显示图片的http链接
            urls: showPosterList, // 需要预览的图片http链接列表
        });
    },
    selectFile(files) {
        console.log("files", files);
        // 返回false可以阻止某次文件上传
    },
    uplaodFile(files) {
        console.log("upload files", files);
        const { tempFilePaths } = files;
        // 文件上传的函数，返回一个promise
        return new Promise((resolve, reject) => {
            const img_list = [],
                error_list = [];
            let count = 0;
            for (let i = 0; i < tempFilePaths.length; i++) {
                wx.uploadFile({
                    url: api.leader.uploadImageUrl, //仅为示例，非真实的接口地址
                    filePath: tempFilePaths[i],
                    name: "file",
                    // formData: {
                    //   'user': type
                    // },
                    success(result) {
                        wx.hideLoading();
                        count++;
                        if (result.statusCode === 413) {
                            // reject("图片太大了");
                            wx.showToast({
                                title: "图片太大了",
                                icon: "error",
                            });
                            error_list[i] = tempFilePaths[i];
                            img_list.push(tempFilePaths[i]);
                        } else {
                            result.data = JSON.parse(result.data);
                            const data = result.data.message;
                            img_list.push(data);
                        }
                        console.log("img_list", img_list);
                        if (count === tempFilePaths.length) {
                            if (img_list.length > 0) {
                                resolve({
                                    urls: img_list,
                                    error: error_list
                                });
                            } else {
                                reject();
                            }
                        }
                    },
                });
            }
        });
    },
    uploadError(e) {
        console.log("upload error", e.detail);
    },
    uploadSuccess(e) {
        const type = e.target.dataset.type,
            urls = e.detail.urls,
            error_list = e.detail.error;
        console.log("upload success", e.detail);
        console.log("upload success", type);
        const data = this.data[type];
        let list = urls.map((item, index) => {
            let obj = {};
            obj.url = item;
            if(error_list[index]){
                obj.error = true
            }
            return obj;
        });
        this.setData({
            [type]: data.concat(list),
        });
    },
    handleDelete(e) {
        const { index } = e.detail.index;
        console.log("e.detail", e.detail.index);
        let pics = this.data.auditPoster;
        pics.splice(index, 1);
        this.setData({
            auditPoster: pics,
        });
    },
    handleDelete1(e) {
        const { index } = e.detail.index;
        console.log("e.detail", e.detail.index);
        let pics = this.data.showPoster;
        pics.splice(index, 1);
        this.setData({
            showPoster: pics,
        });
    },
});
